package day4.problem2;

import java.util.*;

//单词搜索
//https://www.nowcoder.com/practice/987f2981769048abaf6180ed63266bb2?tpId=196&tqId=39583&ru=/exam/oj


public class Solution {
    int n = 0, m = 0;
    boolean[][]st;
    String word;
    public boolean exist (String[] board, String word) {
        n = board.length; m = board[0].length();
        this.word = word;
        st = new boolean[n][m];
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                if(board[i].charAt(j) == word.charAt(0)) {
                    st[i][j] = true;
                    if(dfs(board, i, j, 1)) {
                        return true;
                    }
                    st[i][j] = false;
                }
            }
        }
        return false;
    }

    int[] xx = {0, 0, 1, -1};
    int[] yy = {1, -1, 0, 0};

    private boolean dfs(String[] board, int x, int y, int u) {
        if(u == word.length()) {
            return true;
        }
        for(int i = 0; i<4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && !st[dx][dy] && board[dx].charAt(dy) == word.charAt(u)) {
                st[dx][dy] = true;
                if(dfs(board, dx, dy, u + 1)) return true;
                st[dx][dy] = false;
            }
        }
        return false;
    }
}